package com.shivandragon.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import com.shivandragon.utils.AuthorizationManager;
import com.shivandragon.utils.AuthorizationManager.Authorization;
import com.shivandragon.utils.CharEscapeUtils;
import com.shivandragon.utils.MongoModelUtils;
import com.shivandragon.utils.MongoSingletonHolder;

public class PresentationController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private AuthorizationManager authorizationManager = new AuthorizationManager();
	private MongoSingletonHolder mongoSingletonHolder = MongoSingletonHolder.getInstance();
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if(!authorizationManager.getAuthorisation(request).equals(Authorization.ADMIN)) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;	
		}
		String id = request.getParameter("_id");
		if(id!=null && !id.equals("")) {
			DBObject presentationData = mongoSingletonHolder.getPresentationsDBCollection().findOne(new BasicDBObject("_id", new ObjectId(id)));
			presentationData.put("_id", id);
			for(int i  =0; i < PrezConstants.MAX_IMAGES_PER_PREZ; i++) {
				if(presentationData.get("img"+i)!=null && !presentationData.get("img"+i).equals("")) {
					presentationData.put("img"+i, "/img?_id="+id+"&slideIndex="+i);
				}
			}
			request.setAttribute("presentationData", JSON.serialize(presentationData));
		}
		request.getRequestDispatcher("/WEB-INF/presentationEdit.jsp").forward(request, response);
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {		
		final DBObject dbObject = new BasicDBObject();
		
		//_id
		ObjectId id = null;
		boolean isUpdate = false;
		if(request.getParameter("_id") != null && !request.getParameter("_id").equals("")) {
			id = new ObjectId(request.getParameter("_id"));
			isUpdate = true;
		} else {
			id = new ObjectId();
			dbObject.put("_id", id);
			dbObject.put("creationDate", new Date());			
		}
		
		//title
		if(request.getParameter("title") != null) {
			MongoModelUtils.addFiledValue(dbObject, "title", CharEscapeUtils.escape(request.getParameter("title")), isUpdate);
		}
		
		//slides
		for(int i = 0; i < PrezConstants.MAX_IMAGES_PER_PREZ; i++) {
			String imgSrcStr = request.getParameter("img"+i);
			if("REMOVED".equals(imgSrcStr)) {
				DBObject removeDBObject = null;
				if(dbObject.get("$unset") == null) {
					removeDBObject = new BasicDBObject();
					dbObject.put("$unset", removeDBObject);
				} else {
					removeDBObject = (DBObject) dbObject.get("$unset");
				}
				removeDBObject.put("img"+i, "");
				removeDBObject.put("imgWidth"+i, "");
				removeDBObject.put("imgHeight"+i, "");
				removeDBObject.put("imgDesc"+i, "");
				continue;
			} else if(imgSrcStr!=null && !imgSrcStr.equals("") && !imgSrcStr.startsWith("/img")){
				byte[] imgBytes = DatatypeConverter.parseBase64Binary(imgSrcStr.substring("data:image/png;base64,".length()));
				MongoModelUtils.addFiledValue(dbObject, "img"+i, imgBytes, isUpdate);
			}
			String imgWidthStr = request.getParameter("imgWidth"+i);
			String imgHeightStr = request.getParameter("imgHeight"+i);
			String imgDescStr = request.getParameter("imgDesc"+i);
			if(imgWidthStr!=null && !imgWidthStr.equals("")) {
				MongoModelUtils.addFiledValue(dbObject, "imgWidth"+i, Integer.parseInt(imgWidthStr), isUpdate);
			}
			if(imgHeightStr!=null && !imgHeightStr.equals("")) {
				MongoModelUtils.addFiledValue(dbObject, "imgHeight"+i, Integer.parseInt(imgHeightStr), isUpdate);
			}
			if(imgDescStr!=null) {
				MongoModelUtils.addFiledValue(dbObject, "imgDesc"+i, CharEscapeUtils.escape(imgDescStr), isUpdate);
			}
		}
		
		if((isUpdate && (dbObject.get("$set")!=null || dbObject.get("$unset")!=null)) || !isUpdate) {
			final ObjectId idFinal = id;
			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {
					mongoSingletonHolder.getPresentationsDBCollection().update(new BasicDBObject("_id", idFinal), dbObject, true, false);
				}
				
			});
			t.start();
			try {
				t.join(15000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		response.getWriter().print(id.toStringMongod());
		response.getWriter().flush();
	}

}
